<!-- 新版首页 -->
<template>
  <s-layout
    title="首页"
    navbar="custom"
    tabbar="/pages/index/home/home"
    :bgStyle="jsonConfig.page"
    :navbarStyle="jsonConfig.navigationBar"
    onShareAppMessage
  >
  <view class="home-page">
      <!-- 加载状态 -->
      <view v-if="isLoading" class="loading-container">
        <view class="loading-spinner"></view>
        <text class="loading-text">正在加载配置...</text>
      </view>
      
      <!-- 错误状态 -->
      <view v-else-if="loadError" class="error-container">
        <text class="error-text">{{ loadError }}</text>
        <button class="retry-button" @tap="loadDiyPageConfig">重试</button>
      </view>
      
    <!-- 页面内容 -->
      <view v-else class="page-content">
      <!-- 头部轮播图 -->
      <view class="header-banner">
        <!-- 搜索框悬浮在轮播图上 -->
        <s-home-navbar 
          :searchPlaceholder="searchPlaceholder"
          @search="onSearchClick"
        />
        
        <swiper 
          class="banner-swiper custom-swiper"
          :autoplay="carouselConfig.autoplay"
          :interval="carouselConfig.interval * 1000"
          :duration="carouselConfig.duration"
          :circular="carouselConfig.circular"
          :indicator-dots="false"
          :current="currentBannerIndex"
          @change="onBannerChange"
          style="position: relative;"
        >
          <swiper-item v-for="(item, index) in bannerList" :key="index" @tap="onBannerClick(item)">
            <image 
              class="banner-image" 
              :src="sheep.$url.cdn(item.imgUrl)" 
              mode="aspectFill"
            />
          </swiper-item>
        </swiper>
        
        <!-- 自定义指示器 -->
        <view class="custom-indicators">
          <view 
            v-for="(item, index) in bannerList" 
            :key="index"
            class="custom-dot"
            :class="{ 'active': currentBannerIndex === index }"
          ></view>
        </view>
      </view>

      <!-- 菜单导航栏 -->
      <s-home-menu 
        :menuData="menuData"
        @menuClick="onMenuClick"
      />

      <!-- 广告魔方 -->
      <s-home-ad-cube 
        :leftAds="leftAds"
        :rightAds="rightAds"
        :bannerConfig="bannerConfig"
        @adClick="onAdClick"
      />

      <!-- 精选内容区域 -->
      <s-home-featured 
        :sectionTitle="sectionTitle"
        :sectionSubtitle="sectionSubtitle"
        :featuredItems="featuredItems"
        :moreUrl="moreUrl"
        @itemClick="onFeaturedItemClick"
        @moreClick="onMoreClick"
      />

      </view>
    </view>

    <!-- 侧边栏组件 -->
    <s-sidebar 
      v-if="sidebarConfig && sidebarConfig.items && sidebarConfig.items.length > 0"
      :position="sidebarConfig.position"
      :top="sidebarTop"
      :items="sidebarConfig.items"
      :style="sidebarConfig.style"
      @itemClick="onSidebarItemClick"
    />
  </s-layout>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue';
  import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import HomeApi from '@/sheep/api/home';

  // 引入组件
  import SLayout from '@/sheep/components/s-layout/s-layout.vue';
  import SHomeNavbar from '@/sheep/components/s-home-navbar/s-home-navbar.vue';
  import SHomeMenu from '@/sheep/components/s-home-menu/s-home-menu.vue';
  import SHomeAdCube from '@/sheep/components/s-home-ad-cube/s-home-ad-cube.vue';
  import SHomeFeatured from '@/sheep/components/s-home-featured/s-home-featured.vue';
  import SSidebar from '@/sheep/components/s-sidebar/s-sidebar.vue';

  // 页面数据
  const currentBannerIndex = ref(0);
  const isLoading = ref(false);
  const loadError = ref(null);

  // JSON配置数据（从后端API获取）
  const jsonConfig = ref({
    page: {
      description: "租车平台首页配置",
      backgroundColor: "#f5f6fa",
      backgroundImage: ""
    },
    navigationBar: {
      bgType: "color",
      bgColor: "#fff",
      bgImg: "",
      styleType: "normal",
      alwaysShow: true,
      mpCells: [
        {
          type: "text",
          textColor: "#111111"
        }
      ],
      otherCells: [
        {
          type: "text",
          textColor: "#111111"
        }
      ],
      _local: {
        previewMp: true,
        previewOther: false
      }
    },
    components: []
  });

  // 从JSON配置中解析数据
  const bannerList = computed(() => {
    const carouselComponent = jsonConfig.value.components.find(c => c.id === 'Carousel');
    return carouselComponent ? carouselComponent.property.items : [];
  });

  const carouselConfig = computed(() => {
    const carouselComponent = jsonConfig.value.components.find(c => c.id === 'Carousel');
    if (carouselComponent) {
      return {
        autoplay: carouselComponent.property.autoplay || true,
        interval: carouselComponent.property.interval || 3,
        duration: carouselComponent.property.duration || 500,
        circular: carouselComponent.property.circular || true
      };
    }
    return {
      autoplay: true,
      interval: 3,
      duration: 500,
      circular: true
    };
  });

  const searchPlaceholder = computed(() => {
    const navbarComponent = jsonConfig.value.components.find(c => c.id === 'SearchNavbar');
    return navbarComponent ? navbarComponent.property.searchPlaceholder : '搜索感兴趣的车型';
  });

  // 菜单数据（从JSON配置中解析）
  const menuData = computed(() => {
    const menuComponent = jsonConfig.value.components.find(c => c.id === 'MenuSwiper');
    if (menuComponent) {
      return {
        column: menuComponent.property.column,
        list: menuComponent.property.list
      };
    }
    return { column: 5, list: [] };
  });

  // 广告数据（从JSON配置中解析）
  const leftAds = computed(() => {
    const adCubeComponent = jsonConfig.value.components.find(c => c.id === 'AdCube');
    return adCubeComponent ? adCubeComponent.property.leftAds : {};
  });

  const rightAds = computed(() => {
    const adCubeComponent = jsonConfig.value.components.find(c => c.id === 'AdCube');
    return adCubeComponent ? adCubeComponent.property.rightAds : {};
  });

  const bannerConfig = computed(() => {
    const adCubeComponent = jsonConfig.value.components.find(c => c.id === 'AdCube');
    return adCubeComponent ? adCubeComponent.property.bannerConfig : {
    autoplay: true,
    interval: 3000,
    duration: 500
    };
  });

  // 精选内容数据（从JSON配置中解析）
  const featuredItems = computed(() => {
    const featuredComponent = jsonConfig.value.components.find(c => c.id === 'FeaturedContent');
    return featuredComponent ? featuredComponent.property.featuredItems : [];
  });

  const sectionTitle = computed(() => {
    const featuredComponent = jsonConfig.value.components.find(c => c.id === 'FeaturedContent');
    return featuredComponent ? featuredComponent.property.sectionTitle : '精选内容';
  });

  const sectionSubtitle = computed(() => {
    const featuredComponent = jsonConfig.value.components.find(c => c.id === 'FeaturedContent');
    if (!featuredComponent) return '';
    
    // 优先使用组件的sectionSubtitle
    if (featuredComponent.property.sectionSubtitle && featuredComponent.property.sectionSubtitle.trim()) {
      return featuredComponent.property.sectionSubtitle;
    }
    
    // 如果sectionSubtitle为空，使用第一个精选项目的subtitle作为区域副标题
    if (featuredComponent.property.featuredItems && featuredComponent.property.featuredItems.length > 0) {
      const firstItem = featuredComponent.property.featuredItems[0];
      if (firstItem.subtitle && firstItem.subtitle.trim()) {
        return firstItem.subtitle;
      }
    }
    
    return '';
  });

  const moreUrl = computed(() => {
    const featuredComponent = jsonConfig.value.components.find(c => c.id === 'FeaturedContent');
    return featuredComponent ? featuredComponent.property.moreUrl : '/pages/goods/list';
  });

  // 侧边栏配置
  const sidebarConfig = computed(() => {
    const sidebarComponent = jsonConfig.value.components.find(c => c.id === 'Sidebar');
    return sidebarComponent ? sidebarComponent.property : null;
  });

  // 计算侧边栏顶部距离 - 定位到会员中心位置
  const sidebarTop = computed(() => {
    // 轮播图高度: 500rpx
    // 菜单导航栏高度: 约120rpx (包含padding)
    // 广告魔方高度: 400rpx
    // 广告魔方margin-top: 5rpx
    // 广告魔方margin: 5rpx 20rpx 20rpx 20rpx
    
    const bannerHeight = 500; // 轮播图高度
    const menuHeight = 120;   // 菜单高度
    const adCubeMarginTop = 5; // 广告魔方上边距
    const adCubeHeight = 400;  // 广告魔方高度
    
    // 广告魔方右侧区域分为上下两部分，各占一半高度
    const rightTopHeight = adCubeHeight / 2; // 200rpx - 右侧顶部区域高度
    const rightBottomHeight = adCubeHeight / 2; // 200rpx - 右侧底部区域高度（会员中心所在区域）
    
    // 计算到会员中心区域顶部的距离
    const memberCenterAreaTop = bannerHeight + menuHeight + adCubeMarginTop + rightTopHeight;
    
    // 会员中心在底部区域的中心位置，所以需要加上底部区域高度的一半
    const memberCenterCenter = memberCenterAreaTop + (rightBottomHeight / 2);
    
    return `${memberCenterCenter}rpx`;
  });

  // 事件处理函数
  const onBannerClick = (item) => {
    if (item.url) {
      sheep.$router.go(item.url);
    }
  };

  const onBannerChange = (e) => {
    currentBannerIndex.value = e.detail.current;
  };

  const onSearchClick = () => {
    sheep.$router.go('/pages/index/search');
  };

  const onMenuClick = (item) => {
    if (item.url) {
      sheep.$router.go(item.url);
    } else {
    uni.showToast({
      title: `点击了${item.title}`,
      icon: 'none'
    });
    }
  };

  const onAdClick = (item) => {
    if (item.url) {
      sheep.$router.go(item.url);
    } else {
    uni.showToast({
      title: `点击了广告`,
      icon: 'none'
    });
    }
  };

  const onFeaturedItemClick = (item) => {
    if (item.url) {
      sheep.$router.go(item.url);
    } else {
    uni.showToast({
      title: `查看${item.title}`,
      icon: 'none'
    });
    }
  };

  const onMoreClick = () => {
    sheep.$router.go('/pages/goods/list');
  };

  // 侧边栏点击事件
  const onSidebarItemClick = (item) => {
    console.log('侧边栏项目点击:', item);
    // 侧边栏组件已经有自己的弹窗处理逻辑，这里不需要额外的处理
  };



  // API请求函数
  const loadDiyPageConfig = async () => {
    try {
      isLoading.value = true;
      loadError.value = null;
      
      // 请求DIY页面配置
      const { data, code } = await HomeApi.getDiyPageConfig();
      
      if (code === 0 && data && data.property) {
        // 更新JSON配置 - 后端返回的数据在data.property中
        jsonConfig.value = data.property;
      } else {
        throw new Error('配置数据格式错误');
      }
    } catch (error) {
      loadError.value = error.message || '加载配置失败';
      
      uni.showToast({
        title: '配置加载失败，使用默认配置',
        icon: 'none',
        duration: 2000
      });
    } finally {
      isLoading.value = false;
    }
  };


  // 生命周期
  onLoad((options) => {
    loadDiyPageConfig();
  });

  onShow(() => {
    // 页面显示时的逻辑
  });

  onPullDownRefresh(() => {
    loadDiyPageConfig();
    setTimeout(() => {
      uni.stopPullDownRefresh();
      uni.showToast({
        title: '刷新完成',
        icon: 'success'
      });
    }, 1000);
  });


  onMounted(() => {
    // 组件挂载完成
  });
</script>

<style lang="scss" scoped>
.home-page {
  min-height: 100vh;
  background: #f5f6fa;

  .page-content {
    background: #f5f6fa;
    min-height: 100vh;

    .header-banner {
      position: relative;
      margin: 0;
      border-radius: 0;
      overflow: hidden;
      height: 500rpx;

      .banner-swiper {
        width: 100%;
        height: 100%;

        .banner-image {
          width: 100%;
          height: 100%;
        }
      }

      // 自定义指示器样式
      .custom-indicators {
        position: absolute;
        bottom: 100rpx;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        gap: 16rpx;
        z-index: 999;

        .custom-dot {
          width: 16rpx;
          height: 16rpx;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.3);
          transition: all 0.3s ease;

          &.active {
            background: #ffffff;
            transform: scale(1.2);
          }
        }
      }
      
      // 调整指示器位置，与搜索框间距20rpx
      .banner-swiper :deep(.uni-swiper-dots) {
        bottom: 88rpx !important;
        position: absolute !important;
        left: 50% !important;
        transform: translateX(-50%) !important;
        z-index: 999 !important;
      }
      
      // 尝试其他可能的选择器
      :deep(.uni-swiper-wrapper .uni-swiper-dots) {
        bottom: 88rpx !important;
      }
      
      :deep(swiper .uni-swiper-dots) {
        bottom: 88rpx !important;
      }
    }
  }
}

/* 全局样式强制指示器位置 */
.header-banner .banner-swiper .uni-swiper-dots {
  bottom: 88rpx !important;
  position: absolute !important;
}

/* 更强制的选择器 */
.home-page .header-banner .uni-swiper-dots {
  bottom: 88rpx !important;
}

/* 针对不同平台的选择器 */
/* #ifdef H5 */
.banner-swiper .swiper-pagination {
  bottom: 88rpx !important;
}
/* #endif */

/* #ifdef MP-WEIXIN */
/* 限制在home页面内的指示器样式 */
.home-page .wx-swiper-dots {
  bottom: 200rpx !important;
  background: red !important;
}

.home-page swiper .wx-swiper-dots {
  bottom: 200rpx !important;
  background: red !important;
}

.home-page .wx-swiper-dot {
  background: red !important;
}

.home-page .swiper-dots {
  bottom: 200rpx !important;
  background: red !important;
}

.home-page .swiper-pagination {
  bottom: 200rpx !important;
  background: red !important;
}

/* 限制在home页面内的通用选择器 */
.home-page [class*="swiper"] [class*="dot"] {
  bottom: 200rpx !important;
  background: red !important;
}

.home-page .wx-swiper-dot {
  background: rgba(255, 255, 255, 0.3) !important;
}

.home-page .wx-swiper-dot-active {
  background: #ffffff !important;
}

/* 限制在home页面内的多层选择器 */
.home-page swiper .wx-swiper-dots {
  bottom: 88rpx !important;
}

.home-page .banner-swiper .wx-swiper-dots {
  bottom: 88rpx !important;
  position: absolute !important;
}

.home-page .header-banner .banner-swiper .wx-swiper-dots {
  bottom: 88rpx !important;
  left: 50% !important;
  transform: translateX(-50%) !important;
  position: absolute !important;
  z-index: 999 !important;
}

.home-page .custom-swiper .wx-swiper-dots {
  bottom: 88rpx !important;
  position: absolute !important;
}
/* #endif */
</style>

<!-- 微信小程序专用样式 -->
<style lang="scss">
/* #ifdef MP-WEIXIN */
/* 限制在home页面内的样式 */
.home-page .wx-swiper-dots {
  bottom: 88rpx !important;
  position: absolute !important;
}

.home-page .header-banner .custom-swiper .wx-swiper-dots {
  bottom: 88rpx !important;
  position: absolute !important;
  left: 50% !important;
  transform: translateX(-50%) !important;
  z-index: 999 !important;
}

.home-page .custom-swiper .wx-swiper-dots {
  bottom: 88rpx !important;
}

/* 尝试更具体的选择器 */
.home-page view.header-banner swiper.custom-swiper .wx-swiper-dots {
  bottom: 88rpx !important;
}
/* #endif */

/* #ifdef APP-PLUS */
.banner-swiper .uni-swiper-dots {
  bottom: 88rpx !important;
}
/* #endif */

/* 全局样式覆盖 */
:deep(.uni-grid-item) {
  border: none !important;
}

:deep(.uni-grid) {
  border: none !important;
}

/* 菜单栏和广告魔方间距控制 */
.home-menu {
  margin-bottom: 20rpx;
}

/* 页面进入动画 */
.home-page {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  min-height: 400rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #3cc51f;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  color: #666;
  font-size: 28rpx;
}

/* 错误状态样式 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  min-height: 400rpx;
}

.error-text {
  color: #ff4757;
  font-size: 28rpx;
  text-align: center;
  margin-bottom: 40rpx;
  line-height: 1.5;
}

.retry-button {
  background-color: #3cc51f;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

.retry-button:active {
  background-color: #2ba315;
}

/* 旋转动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
